<?php
class categoryService extends commonService{
    private $table=null;//分类表
    private $table2=null;//模块主表
    private $cache_helper=null;//缓存类
    private $mid=null;//mid
    public function __construct(){
        parent::__construct();
        $this->table=table('category');
        $this->cache_helper=new cache_helper();
        
        $this->include_viewer_dir=P_VIEWER.'category/';
		$this->def_temp1='index.php';
		$this->def_temp2='list.php';
		$this->def_temp3='show.php';
    }
    public function my_template($k,$selected=''){
        $tpl='def_temp'.$k;
        $dir=$this->include_viewer_dir;
        $t=template_files($dir);
        unset($t[$this->$tpl]);
        $default="<option value=''>默认模板[{$this->$tpl}]</option>\r\n";
        return $default.form_select($t,$selected);
    }
	public function define_table($mid){
		$module=load_module();
		$this->table2=table($module[$mid]['table']);
        $this->mid=$mid;
	}
    //取得模块全部记录
    private function get_cache_cat_data(){
        $mid=$this->mid;
        $query="select `id`,`parent_id`,`type`,`path`,`childs`,`name`,`dir`,`thumburl`,`linkurl` from `{$this->table}` where `mid`=:mid order by `mysort` asc";
        $info=array();
        $result=$this->m->query($query,array('mid'=>$mid));
        if($result){
            while($row=$this->m->fetch_array($result,'ASSOC')){
                $info[$row['id']]=$row;
            }
            $this->m->free_result($result);
        }
        return $info;
    }

    /**
     * 下拉选择框中的option
     */
    public function with_option($mid){
        $query="select `id`,`parent_id`,`name`,`path`,`type` from `{$this->table}` where `mid`=:mid order by `mysort` asc";
        $info=array();
        $info=$this->m->mselect($query,array('mid'=>$mid));
        if(count($info)){
			$d=$this->getchilder($info);
		}
        return $d;
    }
	//递归操作
	private function getchilder($array,$parent_id = 0){
		static $data = array();
		foreach($array as $v){
			if($v['parent_id']==$parent_id){
				$data[]=$v;
				$this->getchilder($array,$v['id']);
			}
		}
		return $data;
	}
    /*
     * 取得分类的随机背景色 
     */
    public function get_background($n){
        $cate_color=array('#479ac7','#00b271','#b45b3e','#f1f2d7','#e8e8ff');
        return $cate_color[$n%count($cate_color)];
    }
    //统计该分类下的文章数量
    public function get_sub_count($arccat_id){
        $query="select count(*) from `{$this->table2}` where `arccat_id`=:arccat_id";
        return $this->m->get_field($query,array('arccat_id'=>$arccat_id));
    }
    //无缓存
    private function get_parent_id_path($catid, $CATEGORY) {
		if($CATEGORY[$catid]['parent_id'] && $CATEGORY[$catid]['parent_id'] != $catid) {
			$parents = array();
			$cid = $catid;
			while($catid) {
				if($CATEGORY[$cid]['parent_id']) {
					$parents[] = $cid = $CATEGORY[$cid]['parent_id'];
				} else {
					break;
				}
			}
			$parents[] = 0;
			return implode(',', array_reverse($parents)).',';
		} else {
			return '0,';
		}
	}
    /**
     * 添加分类时取得path路径 格式 0,1,2,
     */
    private function get_add_path($parent_id){
        if($parent_id==0){
            return '0,';
        }
        $query="select concat(`path`,`id`,',') from `{$this->table}` where `id`=:id limit 1";
        return $this->m->get_field($query,array('id'=>$parent_id));
    }
	//更新path
	private function update_path($id,$old_path,$new_path){
		$old_path=$old_path.$id.',';
		$new_path=$new_path.$id.',';
		$query="update `{$this->table}` set `path`=replace(`path`,'{$old_path}','{$new_path}') where `path` like '{$old_path}%' ";
		return $this->m->query($query);
	}
    /*
    * 分类缓存
    */
    public function cache_me(){
        $mid=$this->mid;
        $info=$this->get_cache_cat_data();
        return $this->cache_helper->cache_write("category-{$mid}.php",$info,'category');
    }
    //更新childs
    private function update_childs($id){
        $current_category=$this->model->_f($this->table,'*',$id);
        if(empty($current_category)) return false;
        $CATEGORY = $this->get_cache_cat_data();
        $childs = ','.$id;
        $catids = array($id);
        if($current_category['parent_id']){
            $parents=explode(',',trim($current_category['path'],','));
            unset($parents[0]);
            foreach($parents as $v) {
                $a = $CATEGORY[$v]['type'] ? $CATEGORY[$v]['childs'].$childs : $v.$childs;
                $query="update `{$this->table}` set `childs`='{$a}' where `id`='{$v}' limit 1";
                $this->m->query($query);
            }
        }
        $query="update `{$this->table}` set `childs`='{$id}' where `id`='{$id}' limit 1";
        $this->m->query($query);
        return true;
    }
    //修复path
    public function repair_path(){
        $CATEGORY = $this->get_cache_cat_data();
		foreach($CATEGORY as $catid => $category) {
			$CATEGORY[$catid]['path'] = $path = $this->get_parent_id_path($catid, $CATEGORY);
			$this->m->query("update `{$this->table}` set `path`='{$path}' where `id`='{$catid}'");
		}
        return true;
    }
    //修复childs
    public function repair_childs() {
        $mid=$this->mid;
		$CATEGORY = $this->get_cache_cat_data();
		$childs = array();
		foreach($CATEGORY as $catid => $category) {
            $arr = explode(',', trim($category['path'],','));
            unset($arr[0]);
            foreach($arr as $a) {
                isset($childs[$a]) or $childs[$a] = '';
                $childs[$a] .= ','.$catid;
            }
		}
		foreach($CATEGORY as $catid => $category) {
			if(isset($childs[$catid])) {
				$CATEGORY[$catid]['childs'] = $arrchildid = $catid.$childs[$catid];
                $tmp=array_unique(explode(',',$arrchildid));
                natsort($tmp);
                $arrchildid=implode(',',$tmp);
                $query="update `{$this->table}` set `childs`='$arrchildid' WHERE `id`='{$catid}' limit 1";
				$this->m->query($query);
			} else {
				$CATEGORY[$catid]['childs'] = $catid;
                $query="update `{$this->table}` set `childs`='{$catid}' WHERE `id`='{$catid}' limit 1";
				$this->m->query($query);
			}

		}
		//$this->cache_helper->cache_write("category-{$mid}.php",$CATEGORY,'category');
        return true;
	}
    /**
     * 增 code 0失败 1成功
     */
    public function add_(){
        $return=array();
        $vali=validate::check('category',$_POST,'add',array('mid::='=>$_POST['mid']));
        if ($vali) {
            
            $_POST['childs']='';
			$_POST['items']=0;
            $_POST['path']=$this->get_add_path($_POST['parent_id']);
            $r=$this->model->_i($this->table,$_POST);
            if($r){
                $this->update_childs($this->m->insert_id());
                //$this->cache_me();
                $return['code']=1;
                $return['message']='操作成功！';
            }else{
                $return['code']=0;
                $return['message']='操作失败';
            }
        } else {
            $return['code']=0;
            $return['message']=implode("\\n",validate::getMsg());
        }
        return $return;
    }
	//修改分类信息读取
    public function mod($id){
        $id=intval($id);
        if($id>0){
            return $this->model->_f($this->table,'*',$id);
        }
        return false;
    }
	//检查父类合法性 父类不能为自己，不能为其子类 不能是type=0的父类
	public function check_category_for_mod_($catid,$old_parent_id,$new_parent_id){
		if($old_parent_id==$new_parent_id){
			//if($old_parent_id==0) return true;
			//return false;
			return true;
		}
        if($catid==$new_parent_id){
            return false;
        }
		if($new_parent_id==0){
			return true;
		}
		//取得新父类的path type
		$query="select `path`,`type` from `{$this->table}` where `id`=:id limit 1";
		$r=$this->m->select($query,array('id'=>$new_parent_id));
		
		if(in_array($catid,explode(',',rtrim($r['path'],',')))) return false;
		
		if($r['type']==0) return false;
		return true;
	}
	//检查分类是否有子分类 是否有文章
	public function radio_disabled($catid){
		$r=array();
		$query="select `id` from `{$this->table}` where `parent_id`=:catid limit 1";
		$r[0]=intval($this->m->get_field($query,array('catid'=>$catid)));
		
		$query="select `id` from `{$this->table2}` where `arccat_id`=:catid limit 1";
		$r[1]=intval($this->m->get_field($query,array('catid'=>$catid)));
		
		return $r;
	}
    public function mod_($post,$id){
        $result=array();
        $vali=validate::check('category',$post,'mod',array('mid::='=>$post['mid'],'id::!='=>$id));
        if($vali){
			//更新path
			$post['path']=$this->get_add_path($post['parent_id']);
            
    		$result[0]=$this->model->_u($this->table,$post,$id);
			if($result[0]){
				$this->update_path($id,$post['old_path'],$post['path']);
                if($post['parent_id']!=$post['old_parent_id']) $this->repair_childs();
			}
    	}else{
    		$result[0]=false;
            $result[1]="\\n".implode("\\n",validate::getMsg());
    	}
        return $result;
    }
	public function del($id){
		$result=array();
		if($id>0){
			$query="select `id` from `{$this->table}` where `parent_id`=:id limit 1";
			if($this->m->get_field($query,array('id'=>$id))){
				$result[0]=false;
				$result[1]='该分类下有子分类，无法删除！';
			}else{
				$query="select `id` from `{$this->table2}` where `arccat_id`=:id limit 1";
				if($this->m->get_field($query,array('id'=>$id))){
					$result[0]=false;
					$result[1]='该分类下有文章，无法删除！';
				}else{
					$result[0]=$this->model->_d($this->table,$id);
                    if($result[0]){
                        $this->repair_childs();
                        //$this->cache_me();
                    }
				}
			}
		}else{
			$result[0]=false;
		}
		return $result;
	}
//
}
